/**
 * Created by 郝栩彬 on 2017/7/8.
 */
var express= require('express');
var app=express();
var port = 8002;
//数据库模块
var mongoose=require('mongoose');
//定义模板引擎
var swig = require('swig');
var bodyParser=require('body-parser');
//缓存模块
var Cookies = require('cookies');

var User=require('./models/User');
//程序运行，设置cookies
app.use(function(req,res,next){
    req.cookies=new Cookies(req,res);
    // 解析cookie信息
    if(req.cookies.get('userInfo')){
        try {
            req.userInfo=JSON.parse(req.cookies.get('userInfo'));
            // 获取当前用户登录的类型，是否管理员
            User.findById(req.userInfo._id).then(function(userInfo){
                req.userInfo.isAdmin=Boolean(userInfo.isAdmin);
                next();
            });
        }catch(e){
            next();
        }
    }else{
        next();
    }

});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});

swig.setDefaults({cache:false});
//取消模板缓存 上线时取消！
app.use('/public',express.static(__dirname+'/public')); //相对地址返回文件
//静态文件托管
app.engine('html',swig.renderFile);
//设置模板目录
app.set('views','./views');
//注册模板引擎
app.set('view engine','html')
//处理接收请求
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

//设置路由
app.use('/admin',require('./routers/admin'));
app.use('/api',require('./routers/api'));
app.use('/main',require('./routers/main'));
app.use('/tuling',require('./routers/tuling'));
//
// app.listen(port)
// console.log("listen"+port)

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1:27017/jlu',function(err){
    if(err){
        console.log('数据库连接错误！');
    }else{
        console.log('数据库连接成功！');
        app.listen(port);
        console.log('正在监听'+port)
    }

});